package com.definity.toolkit.web.taglib;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;

import com.definity.toolkit.i18n.I18n;
import com.definity.toolkit.i18n.I18nFactory;

public class BreadcrumbTag extends BaseTag {

	private static final long serialVersionUID = 5812015693038150413L;

	private static final String PREFIX = "breadcrumb.";

	private String key;
	private Boolean reset;
	
	public BreadcrumbTag() {
		setReset(false);
	}
	
	public void setKey(String key) {
		this.key = key;
	}
	
	public void setReset(Boolean reset) {
		this.reset = reset;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public int doEndTag() throws JspException {
		StringBuilder html = new StringBuilder();
		html.append("<ul id=\"breadcrumb\"");
		html.append(createStyleClass());
		html.append(">");
		
		HttpSession session = pageContext.getSession();
		List<Breadcrumb> breadcrumbs = (List<Breadcrumb>) session.getAttribute("dwt.breadcrumb");
		if (breadcrumbs == null) {
			breadcrumbs = new ArrayList<BreadcrumbTag.Breadcrumb>();
			session.setAttribute("dwt.breadcrumb", breadcrumbs);
		}
		
		I18n i18n = I18nFactory.getApplication();
		
		if (reset != null && reset) {
			breadcrumbs.clear();
		}
		
		Breadcrumb breadcrumb = new Breadcrumb((String) pageContext.getRequest().getAttribute("url"), key);
		int indexOf = breadcrumbs.indexOf(breadcrumb);
		if (indexOf > -1) {
			List<Breadcrumb> subList = new ArrayList<Breadcrumb>(breadcrumbs.subList(indexOf, breadcrumbs.size()));
			breadcrumbs.removeAll(subList);
		}
		if (breadcrumbs.isEmpty() || !breadcrumbs.get(breadcrumbs.size() - 1).text.equals(breadcrumb.text)) {
			breadcrumbs.add(breadcrumb);
		}

		for (Breadcrumb b : breadcrumbs) {
			html.append("<li>");
			html.append("<a href=\"" + b.url + "\">");
			html.append(i18n.tl(PREFIX + b.text));
			html.append("</a>");
			html.append("</li>");
		}
		html.append("</ul>");
		
		write(html);
		
		return EVAL_PAGE;
	}
	
	public static class Breadcrumb implements Serializable {

		private static final long serialVersionUID = 4239274392722552238L;
		
		final String url;
		final String text;
		
		public Breadcrumb(String url, String text) {
			this.url = url;
			this.text = text;
		}

		public String getUrl() {
			return url;
		}
		
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((url == null) ? 0 : url.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Breadcrumb other = (Breadcrumb) obj;
			if (url == null) {
				if (other.url != null)
					return false;
			} else if (!url.equals(other.url))
				return false;
			return true;
		}

	}
	
}
